// components/Modal.tsx
import React, { useEffect } from 'react'

interface ModalProps {
  show: boolean
  onClose: () => void
  title?: string
  children: React.ReactNode
  footer?: React.ReactNode // ✅ 可选 footer 插槽
}

export default function Modal({
  show,
  onClose,
  title,
  children,
  footer,
}: ModalProps) {
  useEffect(() => {
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', onKeyDown)
    return () => document.removeEventListener('keydown', onKeyDown)
  }, [onClose])

  if (!show) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-gray-950/50">
      <div className="absolute inset-0" onClick={onClose} />
      <div
        className="relative z-10 w-[90%] sm:w-[400px] bg-white rounded-xl p-6 shadow-lg transition-all duration-300"
        onClick={(e) => e.stopPropagation()}
      >
        {title && <h2 className="text-lg font-semibold mb-4">{title}</h2>}

        <div className="text-sm text-gray-700">{children}</div>

        <div className="mt-6 flex justify-end">
          {footer ? (
            footer
          ) : (
            <button
              onClick={onClose}
              className="px-4 py-2 bg-blue-500 text-white text-sm rounded hover:bg-blue-600"
            >
              关闭
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
